package com.example.yichuangyun.mvvm.ui.fragment;

import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentOfficialInfoBinding;
import com.example.yichuangyun.dialog.ContactsCompanyDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.company.CompanyDataModel;
import com.example.yichuangyun.model.company.CompanyDetailsContactsDataModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.ui.activity.AddContactsActivity;
import com.example.yichuangyun.mvvm.ui.fragment.view.OfficialInfoViewModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UiUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 官方信息
 */
public class OfficialInfoFragment extends BaseFragment<FragmentOfficialInfoBinding, OfficialInfoViewModel> {

    private int from;
    private String eid;
    private CompanyDataModel.CompanyModel companyModel;
    private List<CompanyDetailsContactsDataModel.ContactsModel> tels = new ArrayList<>();
    private List<CompanyDetailsContactsDataModel.ContactsModel> fixedTels = new ArrayList<>();
    private List<CompanyDetailsContactsDataModel.ContactsModel> emails = new ArrayList<>();
    private final List<String> tags = new ArrayList<>();

    @Override
    protected OfficialInfoViewModel bindModel() {
        return getViewModel(this, OfficialInfoViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            from = getArguments().getInt(Constant.fromKey);
            companyModel = (CompanyDataModel.CompanyModel) getArguments().getSerializable(Constant.modelKey);
            eid = companyModel.getEid();
            viewModel.initLabelData(mContext, binding, eid);
            binding.setCompanyModel(companyModel);
            Glide.with(mContext).load(companyModel.getLogoUrl()).placeholder(R.mipmap.icon_company_def_logo).into(binding.includeTopDetails.ivCompanyLogo);

            if (!TextUtils.isEmpty(companyModel.getNewStatusCode())) {
                tags.add(UiUtils.getManagementStatus(companyModel.getNewStatusCode()));
            }
            if (companyModel.isWskh()) {
                tags.add(getString(R.string.wskh));
            }
            if (companyModel.getPayTaxeState() == 1) {
                tags.add(getString(R.string.a_nsr));
            }
            binding.includeTopDetails.tagCloudView.setTags(tags);

            if (companyModel.getIndustryCodeList() != null && companyModel.getIndustryCodeList().size() > 0) {
                StringBuilder industryBuilder = new StringBuilder();
                for (String s : companyModel.getIndustryCodeList()) {
                    industryBuilder.append(s).append(",");
                }
                binding.includeTopDetails.tvIndustry.setText(Html.fromHtml(mContext.getString(R.string.industry, industryBuilder.substring(0, industryBuilder.toString().length() - 1)), Html.FROM_HTML_MODE_LEGACY));
            } else {
                binding.includeTopDetails.tvIndustry.setText(Html.fromHtml(mContext.getString(R.string.industry, "--"), Html.FROM_HTML_MODE_LEGACY));
            }

            binding.includeTopDetails.tvCompanyAddress.setText(Html.fromHtml(mContext.getString(R.string.company_address, CommonUtil.setText3(companyModel.getAddress())), Html.FROM_HTML_MODE_LEGACY));
            binding.includeTopDetails.tvReportAddress.setText(Html.fromHtml(mContext.getString(R.string.company_address_report, CommonUtil.setText3(companyModel.getReportAddress())), Html.FROM_HTML_MODE_LEGACY));

            if (companyModel.getWebUrls() != null && companyModel.getWebUrls().size() > 0) {
                StringBuilder webSiteBuilder = new StringBuilder();
                for (String s : companyModel.getWebUrls()) {
                    webSiteBuilder.append(s).append(",");
                }
                binding.includeTopDetails.tvCompanyWebsite.setText(Html.fromHtml(mContext.getString(R.string.company_website, webSiteBuilder.substring(0, webSiteBuilder.toString().length() - 1)), Html.FROM_HTML_MODE_LEGACY));
            } else {
                binding.includeTopDetails.tvCompanyWebsite.setText(Html.fromHtml(mContext.getString(R.string.company_website, "--"), Html.FROM_HTML_MODE_LEGACY));
            }
            binding.ivLike.setImageResource(companyModel.getCollectState() == 0 ? R.mipmap.icon_like_sel : R.mipmap.icon_like_def);
            binding.tvLike.setText(companyModel.getCollectState() == 0 ? mContext.getString(R.string.company_like) : mContext.getString(R.string.company_cancel_like));
            binding.tvLike.setTextColor(companyModel.getCollectState() == 0 ? mContext.getColor(R.color.color_426FFF) : mContext.getColor(R.color.color_8D9AA9));

            viewModel.getContactWay(eid);
            viewModel.getGsBaseInfo(eid);
            viewModel.getGsChangeRecord(eid);
            viewModel.getRiskInfo(eid);
            viewModel.getManageInfo(eid);
            viewModel.getIntellectualProperty(eid);
            viewModel.getInvestment(eid);
        }
    }

    @Override
    protected void initClick() {
        // 联系方式返回结果
        viewModel.contactsDataModelMutableLiveData.observe(this, companyDetailsContactsDataModel -> {
            int totalCount = 0;
            if (null != companyDetailsContactsDataModel.getMobiles() && companyDetailsContactsDataModel.getMobiles().size() > 0) {
                tels = companyDetailsContactsDataModel.getMobiles();
                totalCount += tels.size();
                binding.tvTel.setText(tels.get(0).getNumber());
                binding.tvMoreTel.setVisibility(View.VISIBLE);
                binding.tvMoreTel.setText(mContext.getString(R.string.more_count, tels.size()));
            }
            if (null != companyDetailsContactsDataModel.getPhones() && companyDetailsContactsDataModel.getPhones().size() > 0) {
                fixedTels = companyDetailsContactsDataModel.getPhones();
                totalCount += fixedTels.size();
                binding.tvFixedTel.setText(fixedTels.get(0).getNumber());
                binding.tvMoreFixedTel.setVisibility(View.VISIBLE);
                binding.tvMoreFixedTel.setText(mContext.getString(R.string.more_count, fixedTels.size()));
            }
            if (null != companyDetailsContactsDataModel.getEmails() && companyDetailsContactsDataModel.getEmails().size() > 0) {
                emails = companyDetailsContactsDataModel.getEmails();
                totalCount += emails.size();
                binding.tvEmail.setText(emails.get(0).getNumber());
                binding.tvMoreEmail.setVisibility(View.VISIBLE);
                binding.tvMoreEmail.setText(mContext.getString(R.string.more_count, emails.size()));
            }

            tags.clear();
            if (!TextUtils.isEmpty(companyModel.getNewStatusCode())) {
                tags.add(UiUtils.getManagementStatus(companyModel.getNewStatusCode()));
            }
            if (companyModel.isWskh()) {
                tags.add(getString(R.string.wskh));
            }
            if (companyModel.getPayTaxeState() == 1) {
                tags.add(getString(R.string.a_nsr));
            }
            if (totalCount > 0) {
                tags.add(getString(R.string.tel_count, totalCount));
            }
            binding.includeTopDetails.tagCloudView.setTags(tags);
        });

        viewModel.onDelayClick(binding.llLike, o -> {
            // 0未收藏、1已收藏
            if (companyModel.getCollectState() == 0) {
                viewModel.collectCompany(companyModel);
            } else {
                viewModel.cancelCollectCompany(companyModel.getEid());
            }
        });

        // 收藏成功返回结果
        viewModel.collectSuccessMutableLiveData.observe(this, s -> {
            companyModel.setCollectState(1);
            binding.ivLike.setImageResource(R.mipmap.icon_like_def);
            binding.tvLike.setText(mContext.getString(R.string.company_cancel_like));
            binding.tvLike.setTextColor(mContext.getColor(R.color.color_8D9AA9));
            ToastHelper.show(s);
            if (from == 1) {
                EventBus.getDefault().post(new EventBusModel(Constant.refreshCompanyList, 1));
            }
        });

        // 取消收藏返回结果
        viewModel.cancelCollectSuccessMutableLiveData.observe(this, s -> {
            companyModel.setCollectState(0);
            binding.ivLike.setImageResource(R.mipmap.icon_like_sel);
            binding.tvLike.setText(mContext.getString(R.string.company_like));
            binding.tvLike.setTextColor(mContext.getColor(R.color.color_426FFF));
            ToastHelper.show(s);
            if (from == 1) {
                EventBus.getDefault().post(new EventBusModel(Constant.refreshCompanyList, 0));
            }
        });

        // 手机、固定电话、邮箱
        viewModel.onDelayClick(binding.tvMoreTel, o -> initDialog(tels, 1));
        viewModel.onDelayClick(binding.tvMoreFixedTel, o -> initDialog(fixedTels, 2));
        viewModel.onDelayClick(binding.tvMoreEmail, o -> initDialog(emails, 3));

        // 添加到联系人
        viewModel.onDelayClick(binding.llAddContacts, o -> {
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.flagKey, 2);
            bundle.putString(Constant.nameKey, companyModel.getName());
            bundle.putString(Constant.creditNoKey, companyModel.getCreditNo());
            JumpIntent.jump(getActivity(), AddContactsActivity.class, bundle);
        });

        binding.includeTopDetails.tvCompanyAddress.setOnLongClickListener(view -> {
            if (!TextUtils.isEmpty(companyModel.getAddress())) {
                CommonUtil.copyText(mContext, companyModel.getAddress());
            }
            return false;
        });
        binding.includeTopDetails.tvReportAddress.setOnLongClickListener(view -> {
            if (!TextUtils.isEmpty(companyModel.getReportAddress())) {
                CommonUtil.copyText(mContext, companyModel.getReportAddress());
            }
            return false;
        });
    }

    private void initDialog(List<CompanyDetailsContactsDataModel.ContactsModel> contactsData, int flag) {
        ContactsCompanyDialog contactsCompanyDialog = new ContactsCompanyDialog(mContext, contactsData, flag) {
            @Override
            public void addAddressBook(CompanyDetailsContactsDataModel.ContactsModel contactsModel) {
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.flagKey, 3);
                bundle.putString(Constant.phoneKey, contactsModel.getNumber());
                if (contactsModel.getIsManuaal() == 0) { // 企业年报
                    bundle.putInt(Constant.contactSourceTypeKey, 8);
                } else if (contactsModel.getIsManuaal() == 1) { // 同事通讯录
                    bundle.putInt(Constant.contactSourceTypeKey, 9);
                }
                bundle.putString(Constant.nameKey, companyModel.getName());
                bundle.putString(Constant.creditNoKey, companyModel.getCreditNo());
                JumpIntent.jump(getActivity(), AddContactsActivity.class, bundle);
            }
        };
        contactsCompanyDialog.showDialog();
    }

    public static OfficialInfoFragment newInstance(CompanyDataModel.CompanyModel companyModel, int from) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.fromKey, from);
        bundle.putSerializable(Constant.modelKey, companyModel);
        OfficialInfoFragment fragment = new OfficialInfoFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshCompanyContactsWay)) {
                viewModel.getContactWay(eid);
            }
        }
    }
}
